package com.sh.d1.gameserver.cmdhandler;

import com.sh.d1.gameserver.login.LoginService;
import com.sh.d1.gameserver.login.db.UserEntity;
import com.sh.d1.gameserver.msg.GameMsgProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用户登录指令处理器
 */
public class UserLoginCmdHandler implements ICmdHandler<GameMsgProtocol.UserLoginCmd> {
    /**
     * 日志对象
     */
    static private final Logger LOGGER = LoggerFactory.getLogger(UserLoginCmdHandler.class);

    @Override
    public void handle(MyCmdHandlerContext ctx, GameMsgProtocol.UserLoginCmd cmd) {
        if (null == ctx ||
            null == cmd) {
            return;
        }

        String userName = cmd.getUserName();
        String password = cmd.getPassword();

        LOGGER.debug("当前线程 = {}", Thread.currentThread().getName());

        // 获取用户实体
        LoginService.getInstance().userLogin(userName, password, (userEntity) -> {
            this.onUserLogin(ctx, userEntity);
            return null;
        });
    }

    /**
     * 当用户完成登录
     *
     * @param ctx        信道处理器上下文
     * @param userEntity 用户实体
     */
    private void onUserLogin(MyCmdHandlerContext ctx, UserEntity userEntity) {
        if (null == ctx ||
            null == userEntity) {
            return;
        }

        // 将用户 Id 附着到上下文中
        ctx.setFromUserId(userEntity.userId);

        GameMsgProtocol.UserLoginResult.Builder
            resultBuilder = GameMsgProtocol.UserLoginResult.newBuilder();
        resultBuilder.setUserId(userEntity.userId);
        resultBuilder.setUserName(userEntity.userName);
        resultBuilder.setHeroAvatar("");

        if (null != userEntity.heroAvatar) {
            resultBuilder.setHeroAvatar(userEntity.heroAvatar);
        }

        // 构建结果并发送
        GameMsgProtocol.UserLoginResult newResult = resultBuilder.build();
        ctx.writeAndFlush(newResult);
    }
}
